package atm;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 转账界面
 */
public class TransferPanel extends JPanel implements ActionListener {
    private ATMFrame atmFrame;
    private ImageIcon sureImg = new ImageIcon("images/buttonSure.jpg");
    private JButton sureBtn = new JButton(sureImg);
    private JLabel accountLabel = new JLabel("请输入转账账号:");
    private JTextField accountField = new JTextField();
    private JLabel sumLabel = new JLabel("请输入转账款金额:");
    private JTextField sumField = new JTextField();
    private Font font = new Font("黑体", Font.BOLD, 25);

    public TransferPanel(ATMFrame atmFrame) {
        this.atmFrame =  atmFrame;
        this.setLayout(null);
        accountLabel.setBounds(245,200,240,50);
        accountLabel.setFont(font);
        accountField.setBounds(450,200,250,50);
        accountField.setFont(font);
        sumLabel.setBounds(230,260,240,50);
        sumLabel.setFont(font);
        sumField.setBounds(450,260,250,50);
        sumField.setFont(font);
        sureBtn.setBounds(884,240,140,50);
        this.add(accountLabel);
        this.add(accountField);
        this.add(sumLabel);
        this.add(sumField);
        this.add(sureBtn);
        sureBtn.addActionListener(this);
        this.setOpaque(false);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == sureBtn) {
            SuperArray users = atmFrame.getUsers();
            String account = accountField.getText();
            for (int i = 0; i < users.size();i++){
                User user = (User) users.get(i);
                if(user.getAccount().equals(account)){
                    User user1 = atmFrame.getLoginUser();
                    try {
                        user1.setBlance(user1.getBlance() - Double.parseDouble(sumField.getText()));
                    }catch (NumberFormatException e1){
                        JOptionPane.showMessageDialog(this,"格式输入错误");
                        return;
                    }
                    if(user1.getBlance() >= 0){
                        atmFrame.switchPanel("menu");
                    }else if(user1.getBlance() < 0){
                        JOptionPane.showMessageDialog(null,"账户余额不足");
                        return;
                    }
                }else if (atmFrame.getLoginUser().getAccount().equals(account)){
                    JOptionPane.showMessageDialog(null,"不能给自己转账");
                    return;
                }else {
                    JOptionPane.showMessageDialog(null,"账号有误");
                    return;
                }
            }
        }
    }
}
